
#include "SpriteSingle.h"
#include "GraphicFactory.h"

namespace Graphics
{
	
	SpriteSingle::SpriteSingle(void):
		m_WidthZoom(0),
		m_HeightZoom(0),
		m_SrcRect(0,0,0,0)
	{
	}

	SpriteSingle::~SpriteSingle(void)
	{
	}
	
	void SpriteSingle::SetImage(Drawable* pImage)
	{
		Sprite::SetImage(pImage);
		if(pImage == 0)
		{
			m_WidthZoom = 0;
			m_HeightZoom = 0;
			m_SrcRect.SetRect(0,0,0,0);
		}
		else
		{
			this->SetRect(0,0,pImage->GetWidth(),pImage->GetHeight());
		}
	}

	void SpriteSingle::SetZoomX(float zx)
	{
		Sprite::SetZoomX(zx);
		m_WidthZoom = (int)((m_SrcRect.right - m_SrcRect.left) * this->GetZoomX());
	}

	
	void SpriteSingle::SetZoomY(float zy)
	{
		Sprite::SetZoomY(zy);
		m_HeightZoom = (int)((m_SrcRect.bottom - m_SrcRect.top) * this->GetZoomY());
	}

		
	bool SpriteSingle::RenderImpl(void)
	{
		if(this->GetImage() == 0)
		{
			return false;
		}

		Graphic2D* const g = GraphicFactory::getInstance()->GetGraphic2D();
		const Position& p = this->GetPos();

		Rect DestRect(p.x, p.y, p.x + m_WidthZoom, p.y + m_HeightZoom);

		return g->Blt(this->GetImage(),&this->GetRect(),&DestRect,&this->GetInfo());
	}

	
	const Rect& SpriteSingle::GetRect(void)
	{
		return m_SrcRect;
	}
	
	void SpriteSingle::SetRect(const Rect& rect)
	{
		this->SetRect(rect.left,rect.top,rect.right-rect.left,rect.bottom-rect.top);
	}
	
	void SpriteSingle::SetRect(int x, int y, int width, int height)
	{
		Drawable* pImage = this->GetImage();

		// test the rectangle if it is vaild
		if( pImage == 0 || 
			x >= pImage->GetWidth() || 
			y >= pImage->GetHeight() || 
			width < 0 || height < 0 )
		{
			return;
		}

		m_SrcRect.left = x;
		m_SrcRect.right = x + width;
		if(m_SrcRect.right > pImage->GetWidth())
		{
			int d = m_SrcRect.right - pImage->GetWidth();
			width -= d;
			m_SrcRect.right -= d;
		}
		m_SrcRect.top = y;
		m_SrcRect.bottom = y+height;
		if(m_SrcRect.bottom > pImage->GetHeight())
		{
			int d = m_SrcRect.bottom - pImage->GetHeight();
			height -= d;
			m_SrcRect.bottom -= d;
		}

		m_WidthZoom = (int)((m_SrcRect.right - m_SrcRect.left) * this->GetZoomX());
		m_HeightZoom = (int)((m_SrcRect.bottom - m_SrcRect.top) * this->GetZoomY());
	}

}